<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/3/15
  Time: 19:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax局部刷新</title>
    <script type="text/javascript">
        //创建AJAX异步对象
        function createAJAX(){
            var ajax = null;
            try{
                //如果IE5=IE12的话
                ajax = new ActiveXObject("microsoft.xmlhttp");
            }catch(e1){
                try{
                    //如果是非IE的话
                    ajax = new XMLHttpRequest();
                }catch(e2){
                    alert("你的浏览器中不支持异步对象，请换浏览器");
                }
            }
            return ajax;
        }
    </script>
</head>
<body>

当前时间：<span id="time"></span> <br>

<input id="buttonID" value="获取当前时间" type="button">

<%--操作 按钮 事件--%>

<script type="text/javascript">
    document.getElementById("buttonID").onclick =function () {
        var ajax = createAJAX();
        var url ="${pageContext.request.contextPath}/time2";//访问severlet
//        1. 准备
        ajax.open("GET",url);
//        2. 发送
        ajax.send(null);
//        3. 处理回调数据
//        当状态发送改变才会触发该函数
        ajax.onreadystatechange = function () {
            if(ajax.readyState==4){
                if(ajax.status==200){
//                    响应成功 从异步对象中获取服务器响应的html数据
                    var nowStr = ajax.responseText;

                    var span = document.getElementById("time");
                    span.innerHTML=nowStr;
                }
            }
        }
    }
</script>

</body>
</html>
